package com.yunkuhui.www.demo.filter;


import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MyFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) {
		// 在过滤器中使用bean对象，需要运行此行代码
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
			ServletException {
		String localName = req.getLocalName();
		String serverName = req.getServerName();
		System.out.println("MyFilter过滤localName：" + localName);
		System.out.println("MyFilter过滤serverName：" + serverName);
		String contextPath = req.getServletContext().getContextPath();
		System.out.println("contextPath: " + contextPath);
		HttpServletRequest request = (HttpServletRequest) req;
		String requestURI = request.getRequestURI();
		System.out.println("requestURI: " + requestURI);
		if (request.getRequestURI().equals("/demo/interceptor/0")) {
			PrintWriter writer = res.getWriter();
			writer.write("/demo/interceptor/0");
			return;
		}
		chain.doFilter(req, res);
	}
}
